<?php
// +----------------------------------------------------------------------
// | [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Author < 931274989@qq.com >
// +----------------------------------------------------------------------
// | Explain 用户授权回调
// +----------------------------------------------------------------------
namespace app\ymkj\controller;

use EasyWeChat\Foundation\Application;
use think\facade\Session;
use think\facade\Config;
use think\Controller;
use think\Db;

class UserAuth extends Controller
{
  // 授权回调
  public function oauth_callback()
  {
    $options = Config::get('wewhat.wxConfig');
    $app = new Application($options);
    $oauth = $app->oauth;
    // 获取 OAuth 授权结果用户信息
    $user = $oauth->user();
    // 更新写入数据库
    $wewhat_user = $user->getOriginal();
    $info = Db::name('user')->where('openid','=',$wewhat_user['openid'])->find();
    $post = [];
    $post['nickname'] = $wewhat_user['nickname']; // "rm".rand(10000,99999);
    $post['sex'] = $wewhat_user['sex'];
    $post['headimgurl'] = $wewhat_user['headimgurl'];
    $post['openid'] = $wewhat_user['openid'];
    if( $info ) {
      Db::name('user')->where('openid','=',$wewhat_user['openid'])->update($post);
    } else {
      Db::name('user')->insert($post);
    }
    Session::set('wewhat_user',$user->getOriginal());
    $targetUrl = empty(Session::get('target_url')) ? '/' : Session::get('target_url');
    $this->redirect($targetUrl);
  }
}
?>